package org.surthi.app.school;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;
import org.surthi.app.school.bean.Section;
import org.surthi.app.school.bean.StandardClass;

public class ConsoleMain {
	private static final Logger logger = Logger.getLogger(ConsoleMain.class.getName());

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("school.jpa");
		if (entityManagerFactory != null ) {
			logger.info("Entity Manager Factory created!");
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			if (entityManager != null ){
				logger.info("EntityManager Created!");
				StandardClass classOne = new StandardClass();
				classOne.setName("1st Class");				
				
				StandardClass classTwo = new StandardClass();
				classTwo.setName("2nd Class");
				
				Section sectionA = new Section();
				sectionA.setName("A");
				
				Section sectionB = new Section();
				sectionB.setName("B");
				
				classOne.addSectionToClass(sectionA);
				classTwo.addSectionToClass(sectionA);
				classTwo.addSectionToClass(sectionB);
				
				entityManager.getTransaction().begin();				
				entityManager.persist(sectionA);
				entityManager.persist(sectionB);
				entityManager.persist(classOne);
				entityManager.persist(classTwo);
				entityManager.getTransaction().commit();
				
				entityManager.getTransaction().begin();
				List<StandardClass> classes = entityManager.createQuery("from StandardClass", StandardClass.class).getResultList();
				for (StandardClass cls : classes) {
					logger.info("Class : id - "+ cls.getClassId()+" Name - "+ cls.getName() +" Number of Sections : "+ cls.getSections().size());
					for (Section sec : cls.getSections()){
						logger.info("Section - Id: "+ sec.getSectionId()+" Name: "+ sec.getName());
					}
				}				
				List<Section> sectionresults = entityManager.createQuery("from Section", Section.class).getResultList();
				for (Section section : sectionresults) {
					logger.info("Section ID : "+ section.getSectionId()+" Name : " + section.getName()+" Number of classes : "+ section.getClasses().size());
				}
				
				entityManager.getTransaction().commit();
			}
			entityManager.close();
		}
		entityManagerFactory.close();
	}

}
